package com.fanrui.code.handle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import com.fanrui.code.chess.ChessGamerManager;
import com.fanrui.code.chess.IChessGamer;
import com.fanrui.code.common.annotation.Handle;
import com.fanrui.code.dao.UserDao;
import com.fanrui.code.entity.InvitationLog;
import com.fanrui.code.entity.InvitationLogExample;
import com.fanrui.code.entity.InvitationLogMapper;
import com.fanrui.code.entity.SignInfo;
import com.fanrui.code.entity.SignInfoExample;
import com.fanrui.code.entity.SignInfoMapper;
import com.fanrui.code.entity.User;
import com.fanrui.code.entity.UserExample;
import com.fanrui.code.entity.UserMapper;
import com.fanrui.code.family.FamilyDao;
import com.fanrui.code.family.FamilyEntity;
import com.fanrui.code.family.FamilyManager;
import com.fanrui.code.family.FamilyMember;
import com.fanrui.code.family.FamilyTrends;
import com.fanrui.code.message.RequestContext;
import com.fanrui.code.player.Player;
import com.fanrui.code.player.Player.CostOperationResult;
import com.fanrui.code.player.Player.OperationType;
import com.fanrui.code.player.PlayerManager;
import com.fanrui.code.util.SessionUtil;
import com.fanrui.proto.cmd.CurrencyType;
import com.fanrui.proto.cmd.FamilyJobPower;
import com.fanrui.proto.cmd.FamilyMemberInfoCmd;
import com.fanrui.proto.cmd.FamilySimpleInfoCmd;
import com.fanrui.proto.cmd.FamilyTrendsType;
import com.fanrui.proto.cmd.JoinPermission;
import com.fanrui.proto.cmd.NotifyAFK;
import com.fanrui.proto.cmd.PlayerInfoCmd;
import com.fanrui.proto.cmd.ReqAgreeJoin;
import com.fanrui.proto.cmd.ReqAgreeQuit;
import com.fanrui.proto.cmd.ReqBindInvitationCode;
import com.fanrui.proto.cmd.ReqChangeFamilyInfo;
import com.fanrui.proto.cmd.ReqChangeFamilyName;
import com.fanrui.proto.cmd.ReqCheckFamily;
import com.fanrui.proto.cmd.ReqCheckJoinFamilyList;
import com.fanrui.proto.cmd.ReqCheckJoinedFamily;
import com.fanrui.proto.cmd.ReqCheckQuitFamilyList;
import com.fanrui.proto.cmd.ReqCreateFamily;
import com.fanrui.proto.cmd.ReqDisbandFamily;
import com.fanrui.proto.cmd.ReqEixtFamily;
import com.fanrui.proto.cmd.ReqFamilyList;
import com.fanrui.proto.cmd.ReqFreezeMemebers;
import com.fanrui.proto.cmd.ReqGetPlayerInfo;
import com.fanrui.proto.cmd.ReqGetSubordinateList;
import com.fanrui.proto.cmd.ReqHeart;
import com.fanrui.proto.cmd.ReqIsInMahjongTable;
import com.fanrui.proto.cmd.ReqJoinFamily;
import com.fanrui.proto.cmd.ReqLogin;
import com.fanrui.proto.cmd.ReqLogout;
import com.fanrui.proto.cmd.ReqQueryFamily;
import com.fanrui.proto.cmd.ReqQueryFamilyMember;
import com.fanrui.proto.cmd.ReqRemoveMember;
import com.fanrui.proto.cmd.ReqSetJoinPermission;
import com.fanrui.proto.cmd.ReqSign;
import com.fanrui.proto.cmd.ReqSignInfo;
import com.fanrui.proto.cmd.ResAgreeJoin;
import com.fanrui.proto.cmd.ResAgreeQuit;
import com.fanrui.proto.cmd.ResBindInvitationCode;
import com.fanrui.proto.cmd.ResBindInvitationCode.Result;
import com.fanrui.proto.cmd.ResChangeFamilyInfo;
import com.fanrui.proto.cmd.ResChangeFamilyName;
import com.fanrui.proto.cmd.ResCheckFamily;
import com.fanrui.proto.cmd.ResCheckJoinFamilyList;
import com.fanrui.proto.cmd.ResCheckJoinedFamily;
import com.fanrui.proto.cmd.ResCheckQuitFamilyList;
import com.fanrui.proto.cmd.ResCreateFamily;
import com.fanrui.proto.cmd.ResDisbandFamily;
import com.fanrui.proto.cmd.ResEixtFamily;
import com.fanrui.proto.cmd.ResFamilyList;
import com.fanrui.proto.cmd.ResFreezeMemebers;
import com.fanrui.proto.cmd.ResGetPlayerInfo;
import com.fanrui.proto.cmd.ResGetSubordinateList;
import com.fanrui.proto.cmd.ResHeart;
import com.fanrui.proto.cmd.ResIsInMahjongTable;
import com.fanrui.proto.cmd.ResJoinFamily;
import com.fanrui.proto.cmd.ResLogin;
import com.fanrui.proto.cmd.ResLogin.LoginResult;
import com.fanrui.proto.cmd.ResLogout;
import com.fanrui.proto.cmd.ResQueryFamily;
import com.fanrui.proto.cmd.ResQueryFamilyMember;
import com.fanrui.proto.cmd.ResRemoveMember;
import com.fanrui.proto.cmd.ResSetJoinPermission;
import com.fanrui.proto.cmd.ResSign;
import com.fanrui.proto.cmd.ResSignInfo;
import com.fanrui.proto.cmd.SignAward;


/**
 * 玩家请求
 * @author Administrator
 *
 */
public class PlayerHandle {

	/**
	 * 绑定邀请码
	 */
	@Handle
	public void bindInvitationCode(Player player, RequestContext context, ReqBindInvitationCode req) {
		ResBindInvitationCode.Builder res = ResBindInvitationCode.newBuilder();
	    UserExample userExample = new UserExample();
	    userExample.createCriteria().andInvitationCodeEqualTo(req.getInvitationCode());
        List<User> users = new ArrayList<>();
        try(SqlSession session = SessionUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			users = mapper.selectByExample(userExample);
		} catch (Exception e) {
			e.printStackTrace();
		}
        if (users.size()<1) {
			res.setResult(Result.UnUsed);
			context.sendResponse(res.build());
			return;
		}
        User user = new User();
        for(User u:users){
        	if (u!=null) {
				user=u;
				break;
			}
        }
        InvitationLogExample invitationLogExample = new InvitationLogExample();
        invitationLogExample.createCriteria().andInviteeIdEqualTo(player.getId());
        try(SqlSession session = SessionUtil.getSession()) {
			InvitationLogMapper mapper = session.getMapper(InvitationLogMapper.class);
			List<InvitationLog> invitationLogs = mapper.selectByExample(invitationLogExample);
			if (invitationLogs.size()>0) {
				res.setResult(Result.Bindinged);
				context.sendResponse(res.build());
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        InvitationLog invitationLog = new InvitationLog();
        invitationLog.setInviterId(user.getId());
        invitationLog.setInviteeId(player.getId());
        try(SqlSession session = SessionUtil.getSession()) {
			InvitationLogMapper mapper = session.getMapper(InvitationLogMapper.class);
			int num = mapper.insertSelective(invitationLog);
			if (num<1) {
				res.setResult(Result.Failure);
				context.sendResponse(res.build());
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        res.setResult(Result.Success);
		context.sendResponse(res.build());
		return;
	}
	
	/**
	 * 玩家登录大厅服
	 */
	@Handle
	public void login(Player player, RequestContext context, ReqLogin login) {
		ResLogin.Builder res = ResLogin.newBuilder();
		player = new Player(UserDao.getInstance().findUserById(player.getId()));
		player.save();
		res.setPlayerId(player.getPersistKey());
		res.setPlayerInfo(player.toCmd());
		res.setResult(LoginResult.Success);
		res.setTime(System.currentTimeMillis());
		context.sendResponse(res.build());
		// 查询是否在游戏中
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		if(gamer != null && gamer.getTable() != null){
			gamer.setAFK(false);
			NotifyAFK.Builder notify = NotifyAFK.newBuilder();
			notify.setIsAfk(false);
			notify.setUserID(player.getId());
			gamer.getTable().broadcast(notify.build());
		}
	}
	
	/**
	 * 玩家退出
	 */
	@Handle
	public void logOut(Player player, RequestContext context, ReqLogout req) {
		// 处理玩家退出登录请求
		// 2.保存数据
		player.save();
		ResLogout.Builder res = ResLogout.newBuilder();
		context.sendResponse(res.build());
	}
	
	/**
	 * 心跳
	 */
	@Handle
	public void heart(Player player, RequestContext context, ReqHeart req) {
		context.sendResponse(ResHeart.newBuilder().build());
	}
	
	/**
	 * 检查是否已在游戏
	 */
	@Handle
	public void CheckGamingTable(Player player, RequestContext context, ReqIsInMahjongTable req) {
		ResIsInMahjongTable.Builder res = ResIsInMahjongTable.newBuilder();
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		int roomID = -1;
		if(gamer != null && gamer.getTable() != null){
			roomID = gamer.getTable().getID();
		}
		res.setRoomID(roomID);
		context.sendResponse(res.build());
	}
	
	/**
	 * 用户信息
	 */
	@Handle
	public void getPlayerInfo(Player player, RequestContext context, ReqGetPlayerInfo req) {
		ResGetPlayerInfo.Builder res = ResGetPlayerInfo.newBuilder();
		res.setPlayerInfo(player.toCmd());
		context.sendResponse(res.build());
	}
	
//	/**
//	 * 签到信息
//	 */
//	@Handle
//	public void getSignInfo(Player player, RequestContext context, ReqSignInfo req) {
//		ResSignInfo.Builder res = ResSignInfo.newBuilder();
////		ConfigFileManager.getInstance().getConfigFileById(Parameter.class, id);
//		res.addAllDays(null);
//		context.sendResponse(res.build());
//	}
	
	/**
	 * 获取下级
	 */
	@Handle
	public void getSubordinateList(Player player, RequestContext context, ReqGetSubordinateList req) {
		ResGetSubordinateList.Builder res = ResGetSubordinateList.newBuilder();
		 InvitationLogExample invitationLogExample = new InvitationLogExample();
	        invitationLogExample.createCriteria().andInviterIdEqualTo(player.getId());
	        List<InvitationLog> invitationLogs = new ArrayList<>();
	        try(SqlSession session = SessionUtil.getSession()) {
				InvitationLogMapper mapper = session.getMapper(InvitationLogMapper.class);
				invitationLogs = mapper.selectByExample(invitationLogExample);
			} catch (Exception e) {
				e.printStackTrace();
			}
	        List<PlayerInfoCmd> playerInfoCmds = new ArrayList<>();
	        for(InvitationLog il:invitationLogs) {
	        	User user = UserDao.getInstance().findUserById(il.getInviteeId());
	        	PlayerInfoCmd.Builder pBuilder = PlayerInfoCmd.newBuilder();
	        	pBuilder.setAccount(user.getAccount())
	        	.setGold(user.getGold())
	        	.setHeadIconUrl(user.getHeadUrl())
	        	.setInvitationCode(user.getInvitationCode())
	        	.setMoney(user.getMoney())
	        	.setNickname(user.getNickname())
	        	.setPlayerId(user.getId())
	        	.setSex(user.getSex());
	        	playerInfoCmds.add(pBuilder.build());
	        }
	       res.addAllSubordinateList(playerInfoCmds); 
	       context.sendResponse(res.build()); 
	}
	

//	/**
//	 * 创建俱乐部
//	 */
//	@Handle
//	public void creatClub(Player player, RequestContext context, ReqCreatClub req) {
//		ResCreatClub.Builder res = ResCreatClub.newBuilder();
//		if (req.getName() == null || StringUtils.isBlank(req.getName())) { // 创建的家族名字为null
//			res.setResult(com.fanrui.proto.cmd.ResCreatClub.Result.NameIllegal);
//			context.sendResponse(res.build());
//			return;
//		}
//		FamilyExample familyExample = new FamilyExample();
//		familyExample.createCriteria().andFamilyNameEqualTo(req.getName());
//		List<Family> families = new ArrayList<>();
//		try(SqlSession session = SessionUtil.getSession()) {
//				FamilyMapper mapper = session.getMapper(FamilyMapper.class);
//				families = mapper.selectByExample(familyExample);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		if (families.size()>0) {
//			res.setResult(com.fanrui.proto.cmd.ResCreatClub.Result.DuplicateName);
//			context.sendResponse(res.build());
//			return;
//		}
//		Family family = new Family();
//		family.setFamilyName(req.getName());
//		family.setFamilyOwer(player.getId());
//		try(SqlSession session = SessionUtil.getSession()) {
//			FamilyMapper mapper = session.getMapper(FamilyMapper.class);
//			int num = mapper.insertSelective(family);
//			if (num<1) {
//				res.setResult(com.fanrui.proto.cmd.ResCreatClub.Result.UnUsed);
//				context.sendResponse(res.build());
//				return;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		res.setResult(com.fanrui.proto.cmd.ResCreatClub.Result.Success);
//		context.sendResponse(res.build());
//		return;
//	}
//	
//	/**
//	 *获取已加入的俱乐部列表
//	 */
//	@Handle
//	public void getMyClubList(Player player, RequestContext context, ReqGetMyClubList req) {
//		ResGetMyClubList.Builder res = ResGetMyClubList.newBuilder();
//		List<FamilyList> familyLists = FamilyListDao.getInstance().queryPlayersClub(player.getId());
//		List<ClubInfo> clubInfos = new ArrayList<>();
//		for(FamilyList fl:familyLists) {
//			Family family = new Family();
//			try(SqlSession session = SessionUtil.getSession()) {
//				FamilyMapper mapper = session.getMapper(FamilyMapper.class);
//				family = mapper.selectByPrimaryKey(fl.getClubId());
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			User user = UserDao.getInstance().findUserById(family.getFamilyOwer());
//			PlayerInfoCmd.Builder pBuilder = PlayerInfoCmd.newBuilder();
//        	pBuilder.setAccount(user.getAccount())
//        	.setGold(user.getGold())
//        	.setHeadIconUrl(user.getHeadUrl())
//        	.setInvitationCode(user.getInvitationCode())
//        	.setMoney(user.getMoney())
//        	.setNickname(user.getNickname())
//        	.setPlayerId(user.getId())
//        	.setSex(user.getSex());
//        	ClubInfo.Builder cBuilder = ClubInfo.newBuilder();
//        	cBuilder.setHolder(pBuilder.build());
//        	cBuilder.setAnnouncement(family.getFamilyNotice());
//        	cBuilder.setId(family.getId());
//        	cBuilder.setName(family.getFamilyName());
//        	cBuilder.setStatus(family.getStatus());
//        	List<FamilyList> familyLists1 = FamilyListDao.getInstance().getFamilyMember(family.getId());
//        	cBuilder.setMembersNumber(familyLists1.size());
//        	clubInfos.add(cBuilder.build());
//		}
//		context.sendResponse(res.build());
//	}
	
	/**
	 *签到
	 */
	@Handle
	public void sign(Player player, RequestContext context, ReqSign req) {
		ResSign.Builder res = ResSign.newBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = new Date();
        String today = sdf.format(dt);
        if (player.getContinuousSignLastTime()!=null || !StringUtils.isBlank(player.getContinuousSignLastTime())) {
        	 if (player.getContinuousSignLastTime().equals(today)) {
             	res.setResult(com.fanrui.proto.cmd.ResSign.Result.IsSign);
             	context.sendResponse(res.build());
     			return;
     		}
		}
        player.setContinuousSignLastTime(today);
        today = today.substring(today.length()-2,today.length());
    	String yDay = today.substring(0, today.length()-1);
    	if (yDay.equals("0")) {
			today=today.substring(today.length()-1,today.length());
		}
    	if (player.getContinuousSignTime()==null || StringUtils.isBlank(player.getContinuousSignTime())) {
    		player.setContinuousSignTime(today);
		}else {
			player.setContinuousSignTime(player.getContinuousSignTime()+","+today);
		}
    	List<SignInfo> signInfos = new ArrayList<>();
    	SignInfoExample signInfoExample = new SignInfoExample();
    	signInfoExample.createCriteria().andDayEqualTo(Integer.valueOf(today));
    	try(SqlSession session = SessionUtil.getSession()) {
			SignInfoMapper mapper = session.getMapper(SignInfoMapper.class);
			signInfos = mapper.selectByExample(signInfoExample);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	SignInfo signInfo = new SignInfo();
    	//检查签到配置是否存在
    	if (player.getContinuousSignDay()==null) {
    		player.setContinuousSignDay(1);
		}else {
			player.setContinuousSignDay(player.getContinuousSignDay()+1);
		}
    	if (signInfos.size()>0) {
			for(SignInfo si:signInfos) {
				if (si!=null) {
					signInfo=si;
					break;
				}
			}
		}
    	if (signInfo.getGold()!=null) {
    	res.setGold(signInfo.getGold());	
    	CostOperationResult c = player.operationCost(CurrencyType.C_Gold, signInfo.getGold(), OperationType.Add);
        if (c.equals(CostOperationResult.OperationFail)) {
			res.setResult(com.fanrui.proto.cmd.ResSign.Result.UnUsed);
			context.sendResponse(res.build());
			return;
		}
    	}
		res.setResult(com.fanrui.proto.cmd.ResSign.Result.Success);
		// 2.保存数据
		player.save();
		context.sendResponse(res.build());
	}

	/**
	 *签到信息
	 */
	@Handle
	public void getSignInfo(Player player, RequestContext context, ReqSignInfo req) {
		ResSignInfo.Builder res = ResSignInfo.newBuilder();
		List<SignInfo> signInfos = new ArrayList<>();
    	SignInfoExample signInfoExample = new SignInfoExample();
    	signInfoExample.createCriteria().andIdIsNotNull();
    	try(SqlSession session = SessionUtil.getSession()) {
			SignInfoMapper mapper = session.getMapper(SignInfoMapper.class);
			signInfos = mapper.selectByExample(signInfoExample);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	List<SignAward> signAwards = new ArrayList<>();
    	for(SignInfo si:signInfos) {
    		SignAward.Builder sBuilder = SignAward.newBuilder();
    		sBuilder.setDay(si.getDay());
    		sBuilder.setGold(si.getGold());
    		sBuilder.setIcoUrl(si.getIconUrl());
    		signAwards.add(sBuilder.build());
    	}
    	String days = player.getContinuousSignTime();
    	if (days!=null || !StringUtils.isBlank(days)) {
    		String[] arr = days.split(",");
        	for (String d:arr) {
        		res.addDays(Integer.valueOf(d));
    		}
		}
    	res.addAllSignAwards(signAwards);
    	context.sendResponse(res.build());
	}
//	/**
//	 * 抽取转盘
//	 */
//	@Handle
//	public void roulette(Player player, RequestContext context, ReqRoulette req) {
//		ResRoulette.Builder res = ResRoulette.newBuilder();
//		// 玩家是否还有抽取轮盘的次数
//		if (player.getCurrencyValue(CurrencyType.C_Roulette) > 0) {
//			// 抽取轮盘
//			com.fanrui.code.item.ItemBag dropItem = DroupGroupMananger.getInstance().getDropItem(ParameterConfigManager.getInstance().getIntParameter(EParameterType.RouletteItem));
//			if(dropItem != null) {
//				// 将抽到的奖励发给玩家，vip玩家获得双倍
//				PlayerData data = new PlayerData(player);
//				ItemBag.Builder itemBag = ItemBag.newBuilder();
//				itemBag.setItemId(dropItem.getItemId());
//				String logStr = "抽取转盘获得：" +  dropItem.getConfig().getItemName();
//				if(player.getVip() > 0) {
//					dropItem.addNum(dropItem.getNum());
//					logStr = "抽取转盘VIP翻倍获得" + dropItem.getConfig().getItemName();
//				}
//				// 添加物品
//				player.addItem(dropItem);
//				player.save();
//				// 日志
//				PlayerLogUtil.log(player, PlayerOpertionType.Routtle, dropItem.getNum(), null, null, null, null, logStr, null, data);
//				// 前端返回
//				itemBag.setItemNum(dropItem.getNum());
//				res.setItem(itemBag.build());
//				res.setResult(ResRoulette.Result.Success);
//			}
//			res.setResult(ResRoulette.Result.UnUsed);
//		}else {
//			res.setResult(ResRoulette.Result.NotHaveNum);
//		}
//		context.sendResponse(res.build());
//	}
	/**
	 * 查看全部家族
	 */
	@Handle
	public void checkFamilyList(Player player, RequestContext context, ReqFamilyList req) {
		Collection<FamilyEntity> familys = FamilyManager.getInstance().findAllFamily();
		Collection<FamilyEntity> lists = new ArrayList<FamilyEntity>();
		if (familys != null && !familys.isEmpty()) {
			for (FamilyEntity fe : familys) {
				if (fe.getMembers().containsKey(player.getId()) && fe.getFamilyLevel() != 0) {
					lists.add(fe);
				}
			}
		}
		ResFamilyList.Builder res = ResFamilyList.newBuilder();
		res.addAllFamilySimpleInfos(FamilyEntity.toSimpleInfo(lists));
		context.sendResponse(res.build());
	}

	/**
	 * 查找家族
	 */
	@Handle
	public void queryFamily(Player player, RequestContext context, ReqQueryFamily req) {
		ResQueryFamily.Builder res = ResQueryFamily.newBuilder();
		// 根据关键字查询
		FamilyEntity family = FamilyDao.getInstance().queryByFamilyName(req.getNameKeyWord());
		// 根据家族id查询
		if (family == null) {
			try {
				family = FamilyDao.getInstance().findById(Integer.parseInt(req.getNameKeyWord()));
			} catch (Exception e) {

			}
		}

		if (family != null) {
			FamilySimpleInfoCmd info = family.toSimpleInfo();
			res.addFamilySimpleInfo(info);
			res.setResult(ResQueryFamily.Result.Success);
		} else {
			res.setResult(ResQueryFamily.Result.NoQuerying);
		}

		// if (familys != null && familys.size() > 0) {
		// for (Family f : familys) {
		// FamilySimpleInfoCmd.Builder familyInfo = FamilySimpleInfoCmd.newBuilder();
		// familyInfo.setCreateTime(f.getFamilyCreateTime().getTime());
		// familyInfo.setFamilylId(f.getId());
		// familyInfo.setFamilyName(f.getFamilyName());
		// familyInfo.setFamilyNotice(f.getFamilyNotice() == null ? "" :
		// f.getFamilyNotice());
		// FamilyDao.getInstance().dbFindByFamilyName(familyName)
		// familyInfo.setFamilyOwerNamer(f.getFamilyOwer().toString());
		// familyInfo.setMemberNum(5);
		// res.addFamilySimpleInfo(familyInfo);
		// }
		// res.setResult(ResQueryFamily.Result.Success);
		// } else {
		// if (res.getResult() != ResQueryFamily.Result.Success)
		// res.setResult(ResQueryFamily.Result.NoQuerying);
		// }
		context.sendResponse(res.build());
	}

	/**
	 * 查找家族成员
	 */
	@Handle
	public void queryFamilyMember(Player player, RequestContext context, ReqQueryFamilyMember req) {
		ResQueryFamilyMember.Builder res = ResQueryFamilyMember.newBuilder();
		FamilyEntity familyEntity = player.getFamilyData();
		// 判断传过来的字符串是否为纯数字,根据id查询
		if (req.getKeyword() != null && StringUtils.isNumeric(req.getKeyword())) {
			FamilyMember member = familyEntity.getFamilyMemberById(Long.parseLong(req.getKeyword()));
			if (member != null) {
				res.addFamilyMemberInfo(member.toMemberInfoCmd());
				res.setResult(ResQueryFamilyMember.Result.Success);
			}
		}
		// 再根据字符串查询
		List<FamilyMemberInfoCmd> members = familyEntity.getFamilyMemberByName(req.getKeyword());
		if (members != null && members.size() > 0) {
			res.addAllFamilyMemberInfo(members);
			res.setResult(ResQueryFamilyMember.Result.Success);
		} else {
			if (res.getResult() != ResQueryFamilyMember.Result.Success)
				res.setResult(ResQueryFamilyMember.Result.NoQuerying);
		}
		context.sendResponse(res.build());

	}

	/**
	 * 创建家族
	 */
	@Handle
	public void createFamily(Player player, RequestContext context, ReqCreateFamily req) {
		ResCreateFamily.Builder res = ResCreateFamily.newBuilder();
		if (req.getFamilyName() == null || StringUtils.isBlank(req.getFamilyName())) { // 创建的家族名字为null
			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.FamilyNameInvalid);
			context.sendResponse(res.build());
			return;
		}

		// if (player.getFamilyData() != null && player.getFamilyData() != null) { //
		// 玩家已经有了家族
		// res.setResult(com.xl.proto.cmd.ResCreateFamily.Result.InFamily);
		// context.sendResponse(res.build());
		// return;
		// }

//		if (req.getSuperior() == null || StringUtils.isBlank(req.getSuperior())) {
//			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//			context.sendResponse(res.build());
//			return;
//		}

		// 先判断填写的是否为官方码
//		String md5Code = Md5Util.getMD5(req.getSuperior());
		// 上级代理
//		int reqSuperior = -1;
//		try{
//			reqSuperior = Integer.valueOf(req.getSuperior());
//		}catch(Exception e){
//			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//			context.sendResponse(res.build());
//			return;
//		}
////		
//		int superior = -1;
//		int familyLevel = -1;
//		List<Integer> officialCode = null;
//		try(SqlSession session = SessionUtil.getSession()) {
//			ParameterMapper pm = session.getMapper(ParameterMapper.class);
//			Parameter parameter = pm.selectByPrimaryKey(EParameterType.officialCode.getType());
//			if(parameter != null){
//				if (parameter != null) {
//					Gson gson = new Gson();
//					officialCode = gson.fromJson(parameter.getValue(), new TypeToken<List<Integer>>() {
//					}.getType());
//				}
//			}
//		} catch (Exception e) {
//			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//			context.sendResponse(res.build());
//			return;
//		}
//		
//		if (officialCode != null && !officialCode.isEmpty() && officialCode.contains(reqSuperior)) {
//			superior = reqSuperior;
//			familyLevel = 0;
//		}
//		// }else{ // 如果不是官方码 判断是否有填写的家族id
//		// try{
//		// superior = Integer.parseInt(req.getSuperior());
//		// FamilyEntity entity = FamilyDao.getInstance().findById(superior);
//		// if(entity == null || entity.getFamilyLevel() >= 2){
//		// res.setResult(com.xl.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//		// context.sendResponse(res.build());
//		// return;
//		// }else{
//		// familyLevel = entity.getFamilyLevel() + 1;
//		// }
//		// }catch(NumberFormatException e){
//		// res.setResult(com.xl.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//		// context.sendResponse(res.build());
//		// return;
//		// }
//		//
//		// }
//		if (familyLevel < 0 || superior < 0) {
//			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.SuperiorCodeErro);
//			context.sendResponse(res.build());
//			return;
//		}

		// if(FamilyManager.getInstance().checkExistFamilyName(req.getFamilyName())){
		// // 名称已经被使用了
		// res.setResult(com.xl.proto.cmd.ResCreateFamily.Result.FamilyNameOccupy);
		// context.sendResponse(res.build());
		// return;
		// }
		boolean canCreate =true;
//		boolean canCreate = ConditionManager.checkPlayerCondition(player,
//				ParameterConfigManager.getInstance().getIntParameter(EParameterType.CreateFamilyCondition));
		if (canCreate) {
//			ActionMananger.execPlayerAction(player,
//					ParameterConfigManager.getInstance().getIntParameter(EParameterType.CreateFamilyCondition));
			FamilyEntity familyEntity = FamilyManager.getInstance().createFamily(req.getFamilyName(), player.getId());

			if (familyEntity != null) {
				player.setFamilyData(familyEntity);
				player.addClubToList(familyEntity);
				player.save();
				familyEntity.setFamilyLevel(1);
				familyEntity.setSuperior(0);
				familyEntity.setStatus((short)1);
				familyEntity.addFamilyMember(player);
				// 加入家族动态
				FamilyTrends familyTreads = new FamilyTrends();
				familyTreads.setPlayerId(player.getId());
				familyTreads.setTime(System.currentTimeMillis());
				familyTreads.setType(FamilyTrendsType.FTT_Create);
				familyTreads.setExpandStr(String.format("玩家%s已创建家族", player.getId()));
				familyEntity.addTrendsList(familyTreads);
				familyEntity.save();
				res.setFamilyInfo(familyEntity.toFamilyInfo(player.getId()));
			}
			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.Success);

		} else {
			res.setResult(com.fanrui.proto.cmd.ResCreateFamily.Result.Condition);
		}
		context.sendResponse(res.build());
	}

	/**
	 * 申请加入
	 */
	@Handle
	public void joinFamily(Player player, RequestContext context, ReqJoinFamily req) {
		ResJoinFamily.Builder res = ResJoinFamily.newBuilder();
		res.setResult(FamilyManager.getInstance().joinFamily(player, req.getFamilyId()));
		context.sendResponse(res.build());

		// if(player.getClubById(req.getFamilyId()) != null || )
		//
		// if (player.getFamilyData() != null || player.getFamilyData() != null) {
		// res.setResult(com.xl.proto.cmd.ResJoinFamily.Result.Joined);
		// context.sendResponse(res.build());
		// } else {
		// // 查找id对应的家族是否存在
		// com.xl.proto.cmd.ResJoinFamily.Result result =
		// FamilyManager.getInstance().joinFamily(player,
		// req.getFamilyId());
		// res.setResult(result);
		// context.sendResponse(res.build());
		// }
	}
	// 查看申请列表
	@Handle
	public void checkJoinFamilyList(Player player, RequestContext context, ReqCheckJoinFamilyList req) {
		FamilyEntity familyEntity = player.getFamilyData();
		ResCheckJoinFamilyList.Builder res = ResCheckJoinFamilyList.newBuilder();
		if (familyEntity != null) {
			Map<Long, Player> applyList = familyEntity.getApplyList();
			if (applyList != null && !applyList.isEmpty()) {
				res.addAllJoinList(PlayerManager.getInstance().playerToSimpleInfoCmd(applyList.values()));
				context.sendResponse(res.build());
				return;
			}
		}
		res.addAllJoinList(Collections.emptyList());
		context.sendResponse(res.build());
	}

	/**
	 * 已经申请的家族列表
	 */
	@Handle
	public void checkJoinedFamily(Player player, RequestContext context, ReqCheckJoinedFamily req) {
		// 查找所有的家族
		Collection<FamilyEntity> FamilyEntitys = FamilyDao.getInstance().findAll();
		ResCheckJoinedFamily.Builder familys = ResCheckJoinedFamily.newBuilder();
		for (FamilyEntity familyEntiy : FamilyEntitys) {
			if (familyEntiy.getApplyList().containsKey(player.getId())) {
				FamilySimpleInfoCmd.Builder familyInfo = FamilySimpleInfoCmd.newBuilder();
				familyInfo.setCreateTime(familyEntiy.getCreateTime().getTime());
				familyInfo.setFamilylId(familyEntiy.getId());
				familyInfo.setFamilyName(familyEntiy.getFamilyName());
				familyInfo.setFamilyNotice(familyEntiy.getFamilyNotice());
				familyInfo.setMemberNum(familyEntiy.getMembers().size());
				familys.addFamilySimpleInfos(familyInfo);
			}
		}

		context.sendResponse(familys.build());
	}

	/**
	 * 同意玩家加入家族
	 */
	@Handle
	public void agreeJoin(Player player, RequestContext context, ReqAgreeJoin req) {
		com.fanrui.proto.cmd.ResAgreeJoin.Result result = FamilyManager.getInstance().agreeJoinFamily(player,
				req.getJoinPlayerId(), req.getAgree());
		ResAgreeJoin.Builder res = ResAgreeJoin.newBuilder();
		res.setResult(result);
		context.sendResponse(res.build());
	}

	/**
	 * 踢出家族
	 */
	@Handle
	public void removeMember(Player player, RequestContext context, ReqRemoveMember req) {
		ResRemoveMember.Result result = FamilyManager.getInstance().removeMemeberFromFamily(player, req.getRemoveMemberId());
		ResRemoveMember.Builder res = ResRemoveMember.newBuilder();
		res.setResult(result);
		context.sendResponse(res.build());
	}

	/**
	 * 退出家族
	 */
	@Handle
	public void exitFamily(Player player, RequestContext context, ReqEixtFamily req) {
		ResEixtFamily.Builder res = ResEixtFamily.newBuilder();
		ResEixtFamily.Result resurt = FamilyManager.getInstance().exitFamily(player);
		res.setResult(resurt);
		context.sendResponse(res.build());
	}
	
	/**
	 * 同意玩家退出家族
	 */
	@Handle
	public void agreeQuit(Player player, RequestContext context, ReqAgreeQuit req) {
		com.fanrui.proto.cmd.ResAgreeQuit.Result result = FamilyManager.getInstance().agreeQuitFamily(player,
				req.getQuitPlayerId(), req.getAgree());
		ResAgreeQuit.Builder res = ResAgreeQuit.newBuilder();
		res.setResult(result);
		context.sendResponse(res.build());
	}
	
	/**
	 * 查看退出家族申请列表
	 */
	@Handle
	public void checkQuitFamilyList(Player player, RequestContext context, ReqCheckQuitFamilyList req) {
		ResCheckQuitFamilyList.Builder res = ResCheckQuitFamilyList.newBuilder();
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null) {
			Map<Long, Player> exitList = familyEntity.getExitList();
			if (exitList != null && !exitList.isEmpty()) {
				res.addAllJoinList(PlayerManager.getInstance().playerToSimpleInfoCmd(exitList.values()));
				context.sendResponse(res.build());
				return;
			}
		}
		res.addAllJoinList(Collections.emptyList());
		context.sendResponse(res.build());
	}
	/**
	 * 查看某个家族
	 */
	@Handle
	public void checkFamily(Player player, RequestContext context, ReqCheckFamily req) {
		ResCheckFamily.Builder res = ResCheckFamily.newBuilder();
		// 查询玩家是否在某一个家族中
		FamilyEntity fm = FamilyDao.getInstance().findById(req.getFamilyId());
		if (fm == null) {
			// 家族不存在
			return;
			// fm.getFamilyMemberById(player.getId()) == null
		} else if (!player.checkHavaClub(req.getFamilyId())) {
			// 该玩家还没有加入该家族
			return;
		} else {
		player.setFamilyData(fm);
		player.save();
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null) {
			res.setFamilyInfo(familyEntity.toFamilyInfo(player.getId()));
		}
		context.sendResponse(res.build());
	}
	}
	/**
	 * 冻结家族成员
	 */
	@Handle
	public void freezeMemeber(Player player, RequestContext context, ReqFreezeMemebers req) {
		ResFreezeMemebers.Builder res = ResFreezeMemebers.newBuilder();
		FamilyEntity fm = player.getFamilyData();
		FamilyMember familyMember1 = fm.getFamilyMemberById(player.getId());
		if (familyMember1.getJobId()<3) {
		FamilyMember familyMember = fm.getFamilyMemberById(req.getUid());
		if (req.getIsFreeze()==true) {
			familyMember.setStatus((short)2);
		}else {
			familyMember.setStatus((short)1);
		}
		player.save();
		res.setResult(com.fanrui.proto.cmd.ResFreezeMemebers.Result.Success);
		res.setUid(req.getUid());
		context.sendResponse(res.build());
		}
		else {
			res.setResult(com.fanrui.proto.cmd.ResFreezeMemebers.Result.LimitedAuthority);
			res.setUid(req.getUid());
			context.sendResponse(res.build());
		}
	}
	/**
	 * 修改家族名字
	 */
	@Handle
	public void changeFamilyName(Player player, RequestContext context, ReqChangeFamilyName req) {
		FamilyEntity familyEntity = player.getFamilyData();
		ResChangeFamilyName.Builder res = ResChangeFamilyName.newBuilder();
		if (familyEntity != null) {
			// 获取操作玩家是否有该权限
//			int jobId = 2;
//			for(FamilyMember fm : familyEntity.getMembers().values()) {
//				if(player.getId() == fm.getPlayer().getId()) {
//					jobId = fm.getJobId();
//				}
//			}
//			boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 2);
//			if (iscan) {
//				familyEntity.setFamilyNotice(req.getInfo());
//				familyEntity.save();
//				res.setResult(ResChangeFamilyInfo.Result.Success);
//			} else {
//				res.setResult(ResChangeFamilyInfo.Result.LimitedAuthority);
//			}
			if(!familyEntity.checkJobPower(player.getId(), FamilyJobPower.Dissolve)){
				res.setResult(ResChangeFamilyName.Result.LimitedAuthority);
			}else {
				familyEntity.setFamilyName(req.getNewName());
				familyEntity.save();
				res.setResult(ResChangeFamilyName.Result.Success);
			}
		} else {
			res.setResult(ResChangeFamilyName.Result.UnUsed);
		}
		context.sendResponse(res.build());
	}
	/**
	 * 修改家族公告消息 1.判断改玩家是否能修改家族公告信息 2.设置家族的公告信息 3.更新家族数据 4.同步给玩家
	 */
	@Handle
	public void changeFamilyInfo(Player player, RequestContext context, ReqChangeFamilyInfo req) {
		FamilyEntity familyEntity = player.getFamilyData();
		ResChangeFamilyInfo.Builder res = ResChangeFamilyInfo.newBuilder();
		if (familyEntity != null) {
			// 获取操作玩家是否有该权限
//			int jobId = 2;
//			for(FamilyMember fm : familyEntity.getMembers().values()) {
//				if(player.getId() == fm.getPlayer().getId()) {
//					jobId = fm.getJobId();
//				}
//			}
//			boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 2);
//			if (iscan) {
//				familyEntity.setFamilyNotice(req.getInfo());
//				familyEntity.save();
//				res.setResult(ResChangeFamilyInfo.Result.Success);
//			} else {
//				res.setResult(ResChangeFamilyInfo.Result.LimitedAuthority);
//			}
			if(!familyEntity.checkJobPower(player.getId(), FamilyJobPower.Dissolve)){
				res.setResult(ResChangeFamilyInfo.Result.LimitedAuthority);
			}else {
				familyEntity.setFamilyNotice(req.getInfo());
				familyEntity.save();
				res.setResult(ResChangeFamilyInfo.Result.Success);
			}
		} else {
			res.setResult(ResChangeFamilyInfo.Result.NoFamily);
		}
		context.sendResponse(res.build());
	}
	
	/**
	 *加入家族设置
	 */
	@Handle
	public void setJoinPermission(Player player, RequestContext context, ReqSetJoinPermission req) {
		ResSetJoinPermission.Builder res = ResSetJoinPermission.newBuilder();
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null) {
			// 获取操作玩家是否有该权限
//			int jobId = 2;
//			for(FamilyMember fm : familyEntity.getMembers().values()) {
//				if(player.getId() == fm.getPlayer().getId()) {
//					jobId = fm.getJobId();
//				}
//			}
//			boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 2);
//			if (iscan) {
//				familyEntity.setFamilyNotice(req.getInfo());
//				familyEntity.save();
//				res.setResult(ResChangeFamilyInfo.Result.Success);
//			} else {
//				res.setResult(ResChangeFamilyInfo.Result.LimitedAuthority);
//			}
			if(!familyEntity.checkJobPower(player.getId(), FamilyJobPower.Dissolve)){
				res.setResult(com.fanrui.proto.cmd.ResSetJoinPermission.Result.LimitedAuthority);
			}else {
				if (req.getJoinPermission()==JoinPermission.NoNeedToAgree) {
					familyEntity.setStatus((short)0);
				}else if (req.getJoinPermission()==JoinPermission.AdministratorAgrees) {
					familyEntity.setStatus((short)1);
				}else {
					familyEntity.setStatus((short)2);
				}
				familyEntity.save();
				res.setResult(com.fanrui.proto.cmd.ResSetJoinPermission.Result.Success);
			}
		} else {
			res.setResult(com.fanrui.proto.cmd.ResSetJoinPermission.Result.UnUsed);
		}
		res.setJoinPermission(req.getJoinPermission());
		context.sendResponse(res.build());
	}

	/**
	 * 解散家族
	 */
	@Handle
	public void exitFamily(Player player, RequestContext context, ReqDisbandFamily req) {
		ResDisbandFamily.Builder res = ResDisbandFamily.newBuilder();
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null) {
			// 族长退出家族 直接解散家族
			if (familyEntity.getOwer().getId() == player.getId()) {
				FamilyManager.getInstance().destoryFamily(familyEntity);
			}else {
				res.setResult(com.fanrui.proto.cmd.ResDisbandFamily.Result.LimitedAuthority);
				context.sendResponse(res.build());
				return;
			}
		}else {
			res.setResult(com.fanrui.proto.cmd.ResDisbandFamily.Result.UnUsed);
			context.sendResponse(res.build());
			return;
		}
		res.setResult(com.fanrui.proto.cmd.ResDisbandFamily.Result.Success);
		context.sendResponse(res.build());
	}
}
